import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios";

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        // 所有列表
        list: [],
        //文本框的内容
        inputValue: '',
        // 下一个id
        nextId: 5,
        // 点击试图默认
        viewKey: 'all'
    },
    getters: {
        // 统计未完成的条数
        unDoneLength(state) {
            return state.list.filter(x => x.done === false).length
        },
        // 根据viewKey值返回对应试图
        infoList(state) {
            if (state.viewKey === 'all') {
                return state.list
            }
            if (state.viewKey === 'undone') {
                return state.list.filter(x => !x.done)
            }
            if (state.viewKey === 'done') {
                return state.list.filter(x => x.done)
            }
            return state.list
        }

    },
    mutations: {
        // 获取所有任务列表数据
        initList(state, list) {
            state.list = list
        },
        // 操作文本框内容
        setInputValue(state, val) {
            state.inputValue = val
        },
        // 添加列表项
        addItem(state) {
            const obj = {
                id: state.nextId,
                info: state.inputValue.trim(),
                done: false
            }
            state.list.push(obj)
            state.nextId++;
            state.inputValue = ""
        },
        // 删除列表项
        removeItem(state, id) {
            const i = state.list.findIndex(x => x.id === id)
            if (i !== -1) {
                state.list.splice(i, 1)
            }
        },
        // 复选框修改转态
        changeStatus(state, param) {
            const i = state.list.findIndex(x => x.id === param.id)
            if (i !== -1) {
                state.list[i].done = param.status
            }
        },
        // 清除已完成的任务
        cleanDone(state) {
            state.list = state.list.filter(x => x.done === false)
        },
        // 修改试图关键字
        changeViewKey(state, key) {
            state.viewKey = key
        }

    },
    actions: {
        getList(context) {
            axios.get('/list.json').then(({ data }) => {
                context.commit('initList', data)
                    // console.log(data);
            })
        }
    },
    modules: {}
})